<?php
use app\api\model\Users;
use app\api\model\UserFinance;
use app\api\model\ShopPayOrder;
use app\api\model\ShopPayOrderGoods;
use app\api\model\UserStore;
use app\api\model\MonthProfit;
use app\api\model\MultiOrder;

function tok($code,$msg,$data=null){
    $res['code'] = $code;
    $res['msg'] = $msg;
    $res['data'] = $data;
    return $res;
}

/**
 * 新版记录用户账务异动
 * @param $user_id 用户ID
 * @param $money 金额
 * @param $money_type 金额类型:1=人民币,2=红包,3=优惠券,4=积分（通券）10积分等于一通券，数据库保存的是通券,5=广告券,6=易物券,7=补贴积分,8=商家红包,9=管理红包,10=消费积分,11=贡献值
 * @param $is_jia 1为增加，2为减少
 * @param $remark 备注
 * @param $connect_id 关联id
 * @param $remaider 增加或减少后余额
 * @param string $order_sn 订单Sn
 * @param int $is_xifang 是否待释放，0为否，1为是
 * @param int $xifang_type 释放类型，1为1倍，2为2倍
 * @param int $is_shop 是否线下店铺的订单，0为否，1为是
 * @param int $is_tbk 是否淘宝订单，0为是，1为否
 * @param int $is_ok_tbk 是否结算淘宝订单，0为否，1为是
 * @param int $is_add 是否加入用户对应的用户字段
 * @param string $remark2 备注2
 *
 */
function new_finance_record($user_id,$money,$money_type,$is_jia,$msg_type,$connect_id,$remaider=0,$order_sn='',$is_xifang=0,$xifang_type=1,$is_shop=0,$is_tbk=0,$is_ok_tbk=0,$is_add=0,$remark2=''){
    $remark = get_finance_msg($msg_type);
    if(!$remark){
        return false;
    }
    log_result('finance_'.$user_id,"用户id:".$user_id."---".$remark."---".$connect_id."---".$money);
    $data['user_id']=$user_id;
    if($is_jia==2){
        $data['money']=$money*-1;
    }else{
        $data['money']=$money;
    }
    $data['msg_type'] = $msg_type;
    $data['money_type']=$money_type;
    $data['is_jia']=$is_jia;
    $data['remark']=$remark;
    $data['connect_id']=$connect_id;
    $data['remaider']=$remaider;
    $data['create_time']=time();
    $data['is_xifang']=$is_xifang;
    $data['xifang_type']=$xifang_type;
    $data['is_shop']=$is_shop;
    $data['is_tbk']=$is_tbk;
    $data['is_ok_tbk']=$is_ok_tbk;
    $data['remark2']=$remark2;
    $data['order_sn']=$order_sn;
    $rs = UserFinance::create($data);
    if($rs){
        return true;
    }else{
        return false;
    }
}
/**
 * 新版记录用户账务异动并添加用户对应账户金额
 * @param $user_id 用户ID
 * @param $money 金额
 * @param $money_type 金额类型:1=人民币,2=红包,3=优惠券,4=积分（通券）10积分等于一通券，数据库保存的是通券,5=广告券,6=易物券,7=补贴积分,8=商家红包,9=管理红包,10=消费积分,11=贡献值
 * @param $is_jia 1为增加，2为减少
 * @param $remark 备注
 * @param $connect_id 关联id
 * @param string $order_sn 订单Sn
 * @param int $is_xifang 是否待释放，0为否，1为是
 * @param int $xifang_type 释放类型，1为1倍，2为2倍
 * @param int $is_shop 是否线下店铺的订单，0为否，1为是
 * @param int $is_tbk 是否淘宝订单，0为是，1为否
 * @param int $is_ok_tbk 是否结算淘宝订单，0为否，1为是
 * @param int $is_add 是否加入用户对应的用户字段
 * @param string $remark2 备注2
 *
 */
function new_finance_record_and_add_money($user_id,$money,$money_type,$is_jia,$msg_type,$connect_id,$order_sn='',$is_xifang=0,$xifang_type=1,$is_shop=0,$is_tbk=0,$is_ok_tbk=0,$is_add=0,$remark2=''){

    $user = Users::where('user_id',$user_id)->find();
    if($is_jia==2){
        $money=$money*-1;
    }
    switch ($money_type){
        case 2:
            $remaider = $user['jindou']+$money;
            $user['jindou'] = $remaider;
            break;
        case 6:
            $remaider = $user['ywq']+$money;
            $user['ywq'] = $remaider;
            break;
        case 11:
            $remaider = $user['contribution']+$money;
            $user['contribution'] = $remaider;
            break;
    }

    $addok = $user->save();//Users::where('user_id',$user_id)->save($adddata);
    if(!$addok){
        return false;
    }

    $remark = get_finance_msg($msg_type);
    if(!$remark){
        return false;
    }
    log_result('finance_'.$user_id,"用户id:".$user_id."---".$remark."---".$connect_id."---".$money);
    $data['user_id']=$user_id;
    $data['money']=$money;

    $data['msg_type'] = $msg_type;
    $data['money_type']=$money_type;
    $data['is_jia']=$is_jia;
    $data['remark']=$remark;
    $data['connect_id']=$connect_id;
    $data['remaider']=$remaider;
    $data['create_time']=time();
    $data['is_xifang']=$is_xifang;
    $data['xifang_type']=$xifang_type;
    $data['is_shop']=$is_shop;
    $data['is_tbk']=$is_tbk;
    $data['is_ok_tbk']=$is_ok_tbk;
    $data['remark2']=$remark2;
    $data['order_sn']=$order_sn;

    $rs= UserFinance::create($data);
    if($rs){
        return true;
    }else{
        return false;
    }
}


/**
 * 获取用户账务异动key值
 * @param $value 值
 * @param int $type 1=根据key获取值，2=根据值获取key
 * @return false|int|mixed|string
 */
function get_finance_msg($value,$type=1){
    if(empty($value)){
        return false;
    }
    $msg_array = config("finance_msg");
    if($type==1){
        return $msg_array[$value];
    }else{
        $key = array_search($value,$msg_array);
        if($key !==false){
            return $key;
        }
        return false;
    }
}


//写入日志
function log_result($file,$str){
    //写入日志
    $nowtime=time();
    $nowdate=date('Y-m-d',$nowtime);
    $nowtime=date('Y-m-d H:i:s',$nowtime);
    $handle = fopen('../runtime/log/'.$nowdate.'-'.$file.'.txt', 'a+');
    $contents = $nowtime."-".$str."\r\n";  // windows下换行是\r\n
    fwrite($handle, $contents);
    fclose($handle);
}

/**
 * 新版分红奖励方法
 * 1。用户购买商品时可选择2种福利政策，福利1即走原有的一套流程。福利2为贡献值。贡献值基数为原奖励基数的5倍
 * 2。购买时使用红包购买，则默认福利2，使用消费券（易物券）购买不进行奖励，使用现金购买可以自由选择福利1，福利2
 * 3。用户获得消费券基数由商家（商品）自行设定
 * 4。修改福利1原有奖励比例，vip、实习经理都按基数的5%奖励。服务经理及以上没有奖励
 * 5。
 * @param $order_id
 *
 */
function new_award($order_id){
    if(!$order_id){
        return -1;exit;//参数错误
    }
    $myorder = ShopPayOrder::where(array('id'=>$order_id))->find();
    if(!$myorder){
        return -3;exit;//订单不存在
    }
    if($myorder['status']!=1&&$myorder['status']!=3&&$myorder['status']!=4){
        return -4;exit;//订单未支付
    }
    $user_id=$myorder['user_id'];
    $user = Users::where(array('user_id'=>$user_id))->find();
    if(!$user){
        return -2;exit;//用户不存在
    }
    //查看是不是这个订单已经结算过奖金
    if($myorder['is_award']==1){
        return -5;exit;//订单已进行过结算
    }

    //根据订单支付方式调用不同结算方法
    if($myorder['money_type']==1){ //现金支付
        //dump("进行现金支付");
        $awardok = award_type1($myorder);
    }else if($myorder['money_type']==2){ //红包支付
        //dump("进行红包支付");
        $awardok = award_type2($myorder);
    }else if($myorder['money_type']==6){ //消费券支付
        //dump("进行消费券支付");
        $awardok = award_type6($myorder);
    }
    //dump("订单结算结果：".$awardok);

    if($awardok){
        //标志订单已结算完成
        ShopPayOrder::where(array('id'=>$order_id))->update(['is_award'=>1]);
        //标志总订单为已结算状态
        ShopPayOrder::where(array('id'=>$myorder['total_order_id']))->update(['status'=>3,'finish_time'=>time()]);
    }
    return $awardok;
}

//现金购买奖励
function award_type1($myorder){
    $trans = true;

    //修改订单状态为已结算
    $odata['status']=3;
    $odata['finish_time']=time();
    $rs = ShopPayOrder::where(['id'=>$myorder['id']])->update($odata);
    if(!$rs){
        $trans = false;
    }
    //dump("订单状态为已结算:".$trans);
    $shop = UserStore::where("user_id",$myorder['shop_user_id'])->find();

    //进行业绩累加
    add_tjmoney($myorder['user_id'],$myorder['order_money']);
    //店铺折扣
    $shop_rebate = empty($shop['give_ratio'])?0.2:$shop['give_ratio']/100; //目前因店铺很多未设置折扣，先以配置文件为准。
    //dump("店铺折扣:".$shop_rebate);
    //获取订单用户上级用户
    $uparray = new_up_user($myorder['user_id']);
    //现金分账
    $shareDetail = array();
    //直推VIP分账
    $vip0_account['amount'] = 0;
    //经理分账
    $vip1_account['amount'] = 0;
    if($myorder['benefit_type']==2){ //福利2，贡献值
        $omoney=$myorder['order_money']*$shop_rebate*config("new_base_contribution");
        //dump("福利2基数：".$omoney);
        //注入利润池
        $totleok = MonthProfit::where('id',1)->setInc("profit",$omoney*config("new_award_pool_ratio"));
        if(!$totleok){
            $trans = false;
        }
        //dump("注入利润池:".$totleok);
        //注入说明,已快递发货时间为区别，如果有则表示是线上订单
        if(empty($myorder['shipping_time'])){
            $profit_msg = "订单核销注入利润值";
        }else{
            $profit_msg = "订单确认收货注入利润值";
        }

        //记录注入原因
        $profitok = MonthProfit::create(['connect_id'=>$myorder['id'],'profit'=>$omoney*config("new_award_pool_ratio"),'msg'=>$profit_msg,'createtime'=>time()]);
        if(!$profitok){
            $trans = false;
        }
        //分配订单用户奖励(用户获得贡献值)
        $userok = new_finance_record_and_add_money($myorder['user_id'],$omoney,11,1,302,$myorder['id'],$myorder['order_sn']);
        if(!$userok){
            $trans = false;
        }
        //dump("分配订单用户奖励：".$userok);
        //分配直推VIP用户奖励
        if($uparray[0]!=null){
            $vok1 = new_finance_record_and_add_money($uparray[0],$omoney*config("new_vip_contribution_ratio"),11,1,303,$myorder['id'],$myorder['order_sn']);
            if(!$vok1){
                $trans = false;
            }
        }
        //dump("分配VIP用户奖励：".$vok1);
        //分配经理奖励
        if($uparray[1]!=null){
            $vok2 = new_finance_record_and_add_money($uparray[1],$omoney*config("new_internship_contribution_ratio"),11,1,303,$myorder['id'],$myorder['order_sn']);
            if(!$vok2){
                $trans = false;
            }
        }
    }else{ //福利1，消费券
        $omoney = get_order_award_money($myorder,$shop_rebate);
        //dump("福利1金额：".$omoney);
        //分配订单用户奖励(用户获得消费券)
        $userok = new_finance_record_and_add_money($myorder['user_id'],$omoney,6,1,201,$myorder['id'],$myorder['order_sn']);
        if(!$userok){
            $trans = false;
        }


        //直推VIP分账
        if($uparray[0]!=null){
            $vip0merchantId = Users::where('user_id',$uparray[0])->value('merchant_id');
            //如果用户已开通乐刷商户，则进行分账，否则获得红包
            if(empty($vip0merchantId)){
                new_finance_record_and_add_money($uparray[0],$omoney*config("new_vip_ywq_ratio"),2,1,101,$myorder['id'],$myorder['order_sn']);
            }
        }
        //经理分账
        if($uparray[1]!=null){
            $vip1merchantId = Users::where('user_id',$uparray[1])->value('merchant_id');
            //如果用户已开通乐刷商户，则进行分账，否则获得红包
            if(empty($vip1merchantId)){
                new_finance_record_and_add_money($uparray[1],$omoney*config("new_internship_ywq_ratio"),2,1,101,$myorder['id'],$myorder['order_sn']);
            }
        }
    }
    //商家分账

    $shop_account['amount'] = 0;
    $shop_account['merchantId'] = $shop['merchant_id'];

    //如果订单使用的是现金支付，并且商家设置的是收现金送券，则现金分账，否则商家100%获取消费券
    if($myorder['shop_money_type']!=2){
        $shopok = new_finance_record_and_add_money($myorder['shop_user_id'],$myorder['order_money'],6,1,202,$myorder['id'],$myorder['order_sn']);
        if(!$shopok){
            $trans = false;
        }
    }
    //分公司分账
    $dialiuserid = get_daili_user($myorder);
    $citymerchantId = Users::where('user_id',$dialiuserid)->value('merchant_id');
    if(empty($citymerchantId) && !empty($dialiuserid)){
        new_finance_record_and_add_money($dialiuserid,$omoney*config("new_city_ywq_ratio"),2,1,401,$myorder['user_id'],$myorder['order_sn']);
    }
    return $trans;
}
//红包购买奖励（红包默认福利2）
function award_type2($myorder){
    $trans = true;

    //修改订单状态为已结算
    $myorder['status']=3;
    $myorder['finish_time']=time();
    $rs=$myorder->save();
    if(!$rs){
        $trans = false;
    }
    //dump("订单状态为已结算:".$trans);
    $shop = UserStore::where("user_id",$myorder['shop_user_id'])->find();
    //商家结算
    $shopok = new_finance_record_and_add_money($myorder['shop_user_id'],$myorder['order_money'],6,1,202,$myorder['id'],$myorder['order_sn']);
    if(!$shopok){
        $trans = false;
    }
    //dump("商家结算:".$trans);
    //暂停推送微信消息
    //send_order_msg3($myorder['id'],4);

    //进行业绩累加
    add_tjmoney($myorder['user_id'],$myorder['order_money']);
    $shop_rebate = empty($shop['give_ratio'])?0.2:$shop['give_ratio']; //目前因店铺很多未设置折扣，默认20%。
    //dump("店铺折扣:".$shop_rebate);
    //获取订单用户上级用户
    $uparray = new_up_user($myorder['user_id']);
    //奖励基数
    $omoney=$myorder['order_money']*$shop_rebate*config("new_base_contribution");
    //dump("福利2基数：".$omoney);
    //注入利润池
    $totleok = MonthProfit::where('id',1)->setInc("profit",$omoney*config("new_award_pool_ratio"));
    if(!$totleok){
        $trans = false;
    }
    //dump("注入利润池:".$totleok);
    //注入说明,已快递发货时间为区别，如果有则表示是线上订单
    if(empty($myorder['shipping_time'])){
        $profit_msg = "订单核销注入利润值";
    }else{
        $profit_msg = "订单确认收货注入利润值";
    }

    //记录注入原因
    $profitok = MonthProfit::create(['connect_id'=>$myorder['id'],'profit'=>$omoney*C("new_award_pool_ratio"),'msg'=>$profit_msg,'createtime'=>time()]);
    if(!$profitok){
        $trans = false;
    }
    //分配订单用户奖励(用户获得贡献值)
    $userok = new_finance_record_and_add_money($myorder['user_id'],$omoney,11,1,302,$myorder['id'],$myorder['order_sn']);
    if(!$userok){
        $trans = false;
    }
    //dump("分配订单用户奖励：".$userok);
    //分配直推VIP用户奖励
    if($uparray[0]!=null){
        $vok1 = new_finance_record_and_add_money($uparray[0],$omoney*config("new_vip_contribution_ratio"),11,1,303,$myorder['id'],$myorder['order_sn']);
        if(!$vok1){
            $trans = false;
        }
    }
    //dump("分配VIP用户奖励：".$vok1);
    //分配经理奖励
    if($uparray[1]!=null){
        $vok2 = new_finance_record_and_add_money($uparray[1],$omoney*config("new_internship_contribution_ratio"),11,1,303,$myorder['id'],$myorder['order_sn']);
        if(!$vok2){
            $trans = false;
        }
    }

    //市代理比例
    $city_ratio = config("new_city_contribution_ratio");
    //市公司奖励
    $citybase = get_order_award_money($myorder,$shop_rebate); //市代理基数以福利1基数为准
    $dialiuserid = get_daili_user($myorder);
    $dailiok = new_finance_record_and_add_money($dialiuserid,$citybase*$city_ratio,2,1,101,$myorder['id'],$myorder['order_sn']);
    if(!$dailiok){
        $trans = false;
    }
    //分公司(分公司与总公司是否只获得红包？)
    //总公司
//    if($trans){
//        Db::commit();
//    }else{
//        Db::rollback();
//    }
    return $trans;
}
//消费券购买奖励
function award_type6($myorder){
    $trans = true;
    //修改订单状态为已结算
    $myorder['status']=3;
    $myorder['finish_time']=time();
    $rs=$myorder->save();
    //("保存订单为已结算：".$rs);
    if(!$rs){
        $trans = false;
    }

    //商家结算 如果订单使用的是消费券购买，则只结算店铺商家
    $shopok = new_finance_record_and_add_money($myorder['shop_user_id'],$myorder['order_money'],6,1,202,$myorder['id'],$myorder['order_sn']);
    //dump("商家结算：".$shopok);
    if(!$shopok){
        $trans = false;
    }
    //dump("商家结算:".$trans);
    //send_order_msg3($myorder['id'],4);

    return $trans;
}
/**
 * 进行业绩累加
 * @param $tjuid 推荐人id
 * @param $money 金额
 */
function add_tjmoney($tjuid,$money){
    $rs1=Users::where(['user_id'=>$tjuid])->find();
    if($rs1){
        if($rs1['is_vip']==1){
            $rs1['all_team_money']=$rs1['all_team_money']+$money;
            $rs2=$rs1->save();
            if($rs2){
                up_vip($tjuid);
            }
        }
        if( $rs1['first_leader']>0){
            add_tjmoney($rs1['first_leader'],$money);
        }
    }
}

/**
 * 晋升通道
 * @param $user_id 晋升人ID
 * @return bool
 */
function up_vip($user_id){
    //暂时关闭晋升通道
    return true;
    //new_up_vip($user_id);
}
/**
 * 新版本升级规则：
 * 1。升级经理至少需要3个VIP下面的用户超100人。
 * 2。升级总监至少需要3个经理
 * 3。升级总经理至少需要3个总监
 * @param $user_id
 */
function new_up_vip($user_id){
    $user=Users::where(array('user_id'=>$user_id,'is_vip'=>1))->find();
    if(!$user){
        return -1;exit; //用户不存在
    }
    if($user['is_vip']!=1){
        return -2;exit; //用户不是VIP
    }
    //本身是vip,检查升级经理条件是否满足
    if($user['vip_level']==0){
        $checkok = check_up_vip($user_id,1);
        if($checkok){
            $user['vip_level'] = 1;
            $user->save();
        }
        new_up_vip($user['first_leader']);
    }
    //本身是经理,检查升级总监条件是否满足
    if($user['vip_level']==1){
        $checkok = check_up_vip($user_id,2);
        if($checkok){
            $user['vip_level'] = 2;
            $user->save();
        }
        new_up_vip($user['first_leader']);
    }
    //本身是总监,检查升级总经理条件是否满足
    if($user['vip_level']==2){
        $checkok = check_up_vip($user_id,3);
        if($checkok){
            $user['vip_level'] = 3;
            $user->save();
        }
    }
}
/**
 * @param $user_id 用户
 * @param $type 类型：１＝升级经理，２＝升级总监，３＝升级总经理
 */
function check_up_vip($user_id,$type){
    if($type==1){
        $vipuser = Users::where(['first_leader'=>$user_id,'is_bind'=>1,'is_vip'=>1,'vip_level'=>0])->select();
        if(count($vipuser)<3){
            return false;
        }
        $oknum = 0;
        foreach ($vipuser as $k=>$v){
            $num = Users::where(['first_leader'=>$v['user_id'],'is_bind'=>1])->count();
            if($num>=100){
                $oknum++;
            }
        }
        if($oknum>=3){
            return true;
        }else{
            return false;
        }
    }
    if($type==2){
        $num2 = Users::where(['first_leader'=>$user_id,'is_bind'=>1,'is_vip'=>1,'vip_level'=>1])->count();
        if($num2>=3){
            return true;
        }else{
            return false;
        }
    }
    if($type==3){
        $num3 = Users::where(['first_leader'=>$user_id,'is_bind'=>1,'is_vip'=>1,'vip_level'=>2])->count();
        if($num3>=3){
            return true;
        }else{
            return false;
        }
    }
    return false;
}
//新版本查询上级
function new_up_user($user_id){
    $arr = array();
    $user = Users::where("user_id",$user_id)->find();
    //查找vip
    $vip0 = recursion_up_user($user['first_leader'],0);
    array_push($arr,$vip0);
    $vip1 = recursion_up_user($user['first_leader'],1);
    array_push($arr,$vip1);
    $vip2 = recursion_up_user($user['first_leader'],2);
    array_push($arr,$vip2);
    $vip3 = recursion_up_user($user['first_leader'],3);
    array_push($arr,$vip3);
    return $arr;
}
function recursion_up_user($user_id,$level){
    $user = Users::where("user_id",$user_id)->find();
    if($user['is_vip']==1 && $user['vip_level']>=$level){
        return $user['user_id'];
    }else{
        if($user['first_leader']>0){
            return recursion_up_user($user['first_leader'],$level);
        }else{
            return null;
        }
    }
}
//获取下级所有客户
function get_lower_user($user_id,&$userList){
    $users = Users::where(['first_leader'=>$user_id])->select();
    if(count($users)>0){
        foreach ($users as $k=>$v){
            array_push($userList,$v['user_id']);
            get_lower_user($v['user_id'],$userList);
        }
    }
}

/**
 * 根据订单及订单商品各自的赠送比例，计算该笔订单应该参与奖励的金额
 * @param $order 订单信息
 * @param $shop_rebate 店铺主赠送比例
 * @return float|int
 */
function get_order_award_money($order,$shop_rebate){
    //获取总订单
    $totalorder = ShopPayOrder::where(['id'=>$order['total_order_id']])->find();
    $ordergoods = ShopPayOrderGoods::where("order_id",$totalorder['id'])->select();
    $money = 0;
    if(count($ordergoods)>0){
        foreach ($ordergoods as $k=>$v){
            if($v['bargain_price']==0){
                $goodsmoney = intval(intval($order['order_money']/$totalorder['order_money']*10000)/10000*$v['total_price']*$v['ratio']*100)/10000;
                $money+=$goodsmoney;
            }
        }
    }else{
        $money=$order['order_money']*$shop_rebate;
    }
    return $money;
}

/**
 * 根据订单信息获取市代理
 * @param $order 订单信息
 * @return null
 */
function get_daili_user($order){
    $city_id = UserStore::where('user_id',$order['shop_user_id'])->value('city_id');
    $city_user = Users::where(['is_daili'=>1,'daili_city'=>$city_id])->find();
    return empty($city_user)?null:$city_user['user_id'];
}

/**
 * 进行订单分账
 * @param $order_id 订单ID
 * @return int
 */
function order_multi_apply($order_id){
    if(!$order_id){
        return -1;exit;//参数错误
    }
    $myorder = ShopPayOrder::where(array('id'=>$order_id))->find();
    if(!$myorder){
        return -3;exit;//订单不存在
    }
    //只有现金订单才参与分账
    if($myorder['money_type']!=1){
        return -6;exit;
    }
    if($myorder['status']!=1&&$myorder['status']!=3&&$myorder['status']!=4){
        return -4;exit;//订单未支付
    }
    $user_id=$myorder['user_id'];
    $user=Users::where(array('user_id'=>$user_id))->find();
    if(!$user){
        return -2;exit;//用户不存在
    }
    //查看是不是这个订单已经进行过分账
    if($myorder['is_account']==1){
        return -5;exit;//订单已进行过结算
    }
    $shareDetail = get_shareDetail($myorder);

    //生成分账订单
    $multi_order['order_id'] = $myorder['id'];
    $multi_order['order_sn'] = $myorder['order_sn'];
    $multi_order['leshua_order_id'] = $myorder['leshua_order_id'];
    //$multi_order['multi_sn'] = $nulti_sn;
    $multi_order['status'] = 0;
    $multi_order['share_detail'] = json_encode($shareDetail);
    $multi_order['create_time'] = time();
    if($mo = MultiOrder::where('order_id',$myorder['id'])->find()){
        MultiOrder::where('order_id',$myorder['id'])->update($multi_order);
        log_result('leshua',"分账-分账订单：".$mo['id']);
    }else{
        $mok = MultiOrder::create($multi_order);
        log_result('leshua',"分账-分账订单：".$mok);
    }
    $shareDetail = merge_list($shareDetail);
    $leshua = new \app\api\controller\Leshua();
    //调用分账接口
    $mok = $leshua->multi_apply($myorder,$shareDetail);
    log_result('leshua',"分账-分账调用结果：".json_encode($mok));
    return $mok;
}

/**
 * 获取订单分账详情
 * @param $order
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function get_shareDetail($order){
    $shareDetail = array();


    $shop = Users::where("user_id",$order['shop_user_id'])->find();
    //商家比例
    $shop_ratio = UserStore::where(['user_id'=>$order['shop_user_id']])->value("give_ratio");
    //$omoney = $order['order_money']*$shop_ratio;
    $origin_money = get_order_award_money($order,$shop_ratio/100);
    $omoney = $origin_money*100;
    $vip0_account['amount'] = 0;
    $vip1_account['amount'] = 0;
    $filiale['amount'] = 0;
    //分账用户
    $uparray = new_up_user($order['user_id']);
    //直推VIP分账
    if($uparray[0]!=null){
        $vip0merchantId = Users::where('user_id',$uparray[0])->value('merchant_id');
        //如果用户已开通乐刷商户，则进行分账，否则获得红包
        if(!empty($vip0merchantId)){
            $vip0_account['merchantId'] = $vip0merchantId;
            $vip0_account['amount'] = intval($omoney*config("new_vip0"));
            $vip0_account['accountType'] = 2;
            $vip0_account['remark'] = "销售分润v0";
            if ($vip0_account['amount']>0){
                array_push($shareDetail,$vip0_account);
            }
        }
    }

    //经理分账
    if($uparray[1]!=null){
        $vip1merchantId = Users::where('user_id',$uparray[1])->value('merchant_id');
        //如果用户已开通乐刷商户，则进行分账，否则获得红包
        if(!empty($vip1merchantId)){
            $vip1_account['merchantId'] = $vip1merchantId;
            $vip1_account['amount'] = intval($omoney*config("new_vip1"));
            $vip1_account['accountType'] = 2;
            $vip1_account['remark'] = "销售分润v1";
            if ($vip1_account['amount']>0){
                array_push($shareDetail,$vip1_account);
            }
        }
    }
    //商家分账
    $shop_account['amount'] = 0;
    $shop_account['merchantId'] = $shop['merchant_id'];

    //如果订单使用的是现金支付，并且商家设置的是收现金送券，则现金分账，否则商家100%获取消费券
    $shopuser = Users::where('user_id',$order['shop_user_id'])->find();
    if($order['shop_money_type'] == 2){
        //如何商家用户有足够消费券，则由商家送消费券给消费都，平台只需要4%
        if($shopuser['ywq']>=$origin_money){
            //扣除商家消费券
            //$syok = new_finance_record_and_add_money($shopuser['user_id'],$origin_money,6,2,204,$order['id'],$order['order_sn']);
            //添加另一种情况，当商家收现金自己送券，且消费者没有推荐人时(自来客)，只收取商家千分之3.8手续费;
            if($uparray[0]==null){
                //商家收现金送券=订单金额*(1-0.0038)/(1-0.0026)
                $shop_account['amount'] = intval($order['order_money']*(1-0.0038)/(1-0.0026)*100);
            }else{
                $shop_account['amount'] = intval($order['order_money']*100-$omoney*(config('new_vip_ywq_ratio')+config("new_internship_ywq_ratio")+config("new_city_ywq_ratio")));
            }
            $shop_account['accountType'] = 2;
            $shop_account['remark'] = "销售收入";
        }else{
            //如果商家消费券不够，则由平台送消费券给消费者，商家全额扣除奖励基数
            $shop_account['amount'] = intval($order['order_money']*100-$omoney);
            $shop_account['accountType'] = 2;
            $shop_account['remark'] = "销售收入";
        }
        if ($shop_account['amount']>0){
            array_push($shareDetail,$shop_account);
        }
    }
    //分公司分账
    $dialiuserid = get_daili_user($order);
    $citymerchantId = Users::where('user_id',$dialiuserid)->value('merchant_id');
    if(!empty($citymerchantId)){
        $filiale['merchantId'] = $citymerchantId;
        //添加另一种情况，当商家收现金自己送券，且消费者没有推荐人时(自来客)，分公司得0.0012;
        if($uparray[0]==null && $order['shop_money_type']==2 && $shopuser['ywq']>=$origin_money){
            //分公司=订单金额*0.0012/(1-0.0026)
            $filiale['amount'] = intval($order['order_money']*0.0012/(1-0.0026)*100);
        }else{
            $filiale['amount'] = intval($omoney*C("new_city"));
        }
        $filiale['accountType'] = 2;
        $filiale['remark'] = "分公司分润";
        if ($filiale['amount']>0){
            array_push($shareDetail,$filiale);
        }
    }
    //总公司分账
    $head_office['merchantId'] = config("payconfig.merchant_id");
    $head_office['amount'] = $order['order_money']*100-$shop_account['amount']-$vip0_account['amount']-$vip1_account['amount']-$filiale['amount'];
    $head_office['accountType'] = 2;
    $head_office['remark'] = "总公司分润";
    if ($head_office['amount']>0){
        array_push($shareDetail,$head_office);
    }
    return $shareDetail;
}

/**
 * 对分账详情中同一商户号的商家进行合并
 * @param $shareDetail
 * @return array
 */
function merge_list($shareDetail){
    $new_detail = array();
    $repeatList = get_array_repeat($shareDetail,"merchantId");
    if(count($repeatList)<=0){
        return $shareDetail;
    }
    foreach ($repeatList as $k=>$v){
        $itemamount=0;
        $remark = '';
        foreach ($v as $k1=>$v1){
            $itemamount+=intval($v1['amount']);
            $remark = $v1['remark'];
        }
        $newdata['merchantId'] = $k;
        $newdata['amount'] = $itemamount;
        $newdata['accountType'] = 2;
        $newdata['remark'] = $remark;
        array_push($new_detail,$newdata);
    }
    return $new_detail;
}
//找出对象数组中指定元素值相同的
function get_array_repeat($arr,$name){
// 用于记录每个属性值对应的对象集合
    $groups = [];
// 按对象的name属性分组
    foreach ($arr as $item) {
        $key = $item[$name]; // 以name属性作为分组依据
        if (!isset($groups[$key])) {
            $groups[$key] = [];
        }
        $groups[$key][] = $item;
    }
// 筛选出值相同（即分组中元素数量>1）的对象组
    $duplicates = [];
    foreach ($groups as $value => $objects) {
        $duplicates[$value] = $objects;
    }
    return $duplicates;
}

/**
 * 发起请求
 * @param string $url
 * @param string $type
 * @param string $arr
 * @param string $head
 * @return bool|string
 */
function http_curl($url = "", $type = 'get', $arr = '',$head = 'application/x-www-form-urlencoded')
{
    $ch = curl_init();
    //2.设置curl的参数
    curl_setopt($ch, CURLOPT_URL, $url); //设置我们的url
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //curl_exec执行成功则返回执行结果
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    if ($type == 'post') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $arr); //将$arr发送给$url
    }
    curl_setopt($ch,CURLINFO_CONTENT_TYPE,$head);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

/**
 * 加密密码
 * @param $str
 * @return string
 */
function encrypt($str){
    return md5(config("AUTH_CODE").$str);
}

//按比例
function get_thumb_image($img, $user_id,$width)
{
    // return $img;
    //判断缩略图是否存在
    $path = "/upload/user/$user_id/thumb/";
    $img = str_replace('/public','',$img);
    $extarr = explode(".",$img);
    $ext = $extarr[count($extarr)-1];
    $pic_name=basename($img);
    if (!is_file('./'.$img)) {
        return '/public/images/icon_goods_thumb_empty_300.png';
    }
    $image_size   =   getimagesize('./'.$img);
    $height=intval($width*($image_size[1]/$image_size[0]));
    $img_thumb_name = $pic_name."_{$width}_{$height}".".".$ext;
    //dump("AAA");
    //这个缩略图 已经生成过这个比例的图片就直接返回了
    if(is_file(".".$path.$img_thumb_name)){
        return $path.$img_thumb_name;
    }
    //dump("BBB");
    $original_img = '.' . $img; //相对路径

    try {
        require_once '../vendor/topthink/think-image/src/Image.php';
        require_once '../vendor/topthink/think-image/src/image/Exception.php';
        if(strstr(strtolower($original_img),'.gif'))
        {
            require_once '../vendor/topthink/think-image/src/image/gif/Encoder.php';
            require_once '../vendor/topthink/think-image/src/image/gif/Decoder.php';
            require_once '../vendor/topthink/think-image/src/image/gif/Gif.php';
        }
        $image = \think\Image::open($original_img);

        // 生成缩略图
        !is_dir($path) && mkdir($path, 0777, true);
        // 参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
        $image->thumb($width, $height, 3)->save(".".$path . $img_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
        $img_url = $path . $img_thumb_name;

        return $img_url;
    } catch (think\Exception $e) {

        return $original_img;
    }
}
//按比例
function get_thumb_image2($img, $user_id,$width)
{
    // return $img;
    //判断缩略图是否存在
    $path = "/upload/user/$user_id/thumb/";
    $img = str_replace('/public','',$img);
    $pic_name=basename($img);
    if (!is_file('./'.$img)) {
        return '/public/images/icon_goods_thumb_empty_300.png';
    }
    $image_size   =   getimagesize('./'.$img);
    $height=intval($width*($image_size[1]/$image_size[0]));
    $img_thumb_name = $pic_name."_{$width}_{$height}";
    //halt(is_link($path . $img_thumb_name));
    //这个缩略图 已经生成过这个比例的图片就直接返回了
    if (is_file($path . $img_thumb_name . '.jpg')) return $path . $img_thumb_name . '.jpg';

    if (is_file($path . $img_thumb_name . '.jpeg')) return $path . $img_thumb_name . '.jpeg';

    if (is_file($path . $img_thumb_name . '.gif')) return $path . $img_thumb_name . '.gif';

    if (is_file($path . $img_thumb_name . '.png')) return $path . $img_thumb_name . '.png';

    $original_img = '.' . $img; //相对路径
    if (!is_file($original_img)) {
        return '/public/images/icon_goods_thumb_empty_300.png';
    }

    try {
        require_once '../vendor/topthink/think-image/src/Image.php';
        require_once '../vendor/topthink/think-image/src/image/Exception.php';
        if(strstr(strtolower($original_img),'.gif'))
        {
            require_once '../vendor/topthink/think-image/src/image/gif/Encoder.php';
            require_once '../vendor/topthink/think-image/src/image/gif/Decoder.php';
            require_once '../vendor/topthink/think-image/src/image/gif/Gif.php';
        }
        $image = \think\Image::open($original_img);
        $img_thumb_name = $img_thumb_name . '.' . $image->type();
        // 生成缩略图
        !is_dir($path) && mkdir($path, 0777, true);
        // 参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
        $imgok = $image->thumb($width, $height, 3)->save(".".$path . $img_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
        $img_url = $path . $img_thumb_name;

        return $img_url;
    } catch (think\Exception $e) {

        return $original_img;
    }
}

/**
 * 格式化字符，保留4位小数，如果第4位是0则保留3位，如果第3位还是0则保留2位。
 * @param $str
 * @return string
 */
function str_format_two($str){
    $newstr = number_format($str,4);
    if(substr($newstr,-1) == '0'){
        $newstr = substr($newstr, 0, -1);
    }
    if(substr($newstr,-1) == '0'){
        $newstr = substr($newstr, 0, -1);
    }
    return $newstr;
}

/**
 * 获取唯一订单号
 * @param int $type 1=易物订单sn,2=普通订单sn,3=易物订单核销码
 */
function get_order_sn($type=1){
    $order_sn = null;
    if($type==1){
        // 保证不会有重复订单号存在
        while(true){
            $order_sn = "shop".date('YmdHis').rand(1000,9999); // 订单编号
            $order_sn_count = ShopPayOrder::where(array('order_sn' => $order_sn))->count();
            if($order_sn_count == 0)
                break;
        }
    }
    if($type==3){
        while(true){
            $order_sn = rand(10000000,99999999); //核销码
            $order_count = ShopPayOrder::where(array('hexiao_code' => $order_sn,'status'=>array('in',[0,1])))->count();
            if($order_count == 0)
                break;
        }
    }
    return $order_sn;
}

/**
 * 计算时间差
 * @param $timestamp
 * @return array
 */
function calculateTimeDifference($timestamp)
{
    // 获取当前时间的时间戳（秒）
    $currentTime = time();
    // 计算时间差（秒）
    $timeDiff = $timestamp - $currentTime;
    // 计算天数
    $days = floor($timeDiff / (24 * 3600));
    // 计算剩余秒数
    $remainder = $timeDiff % (24 * 3600);
    // 计算小时数
    $hours = floor($remainder / 3600);
    // 计算剩余秒数
    $remainder %= 3600;
    // 计算分钟数
    $minutes = floor($remainder / 60);
    // 计算剩余秒数
    $seconds = $remainder % 60;
    return [
        'days' => $days,
        'hours' => $hours,
        'minutes' => $minutes,
        'seconds' => $seconds
    ];
}

function get_image($imgurl){
    $url = unserialize($imgurl);
    if(is_array($url)){
        $url = $url[0];
    }
    $img = str_replace('/public','',$url);
    return config('img_url').$img;
}